//
//  MBDAvatarPickerViewController.swift
//  MasterBoy
//
//  Created by kyson on 2023/6/13.
//

import Foundation
import UIKit
import LGAlertView
import SnapKit

import SwiftyJSON
import MJRefresh
import Alamofire
import Kingfisher
import Toast_Swift
import Kingfisher

import CoreServices

class MBDAvatarPickerViewController : MBDBaseViewController {
    var avatarImageView : UIImageView!
    var detailImageURL : String?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //防止push过程中的黑边
        self.view.setDynamicBackgroundColor()
        
        let rightItem = UIButton(frame: CGRectMake(0, 0, 45, 25))
        rightItem.setImage(UIImage(named: "ico_more"), for: .normal)
        rightItem.addTarget(self, action: #selector(rightItemPressed), for: .touchUpInside)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightItem)
        
        avatarImageView = UIImageView()
        
        let url = URL.init(string: MBDPath2URLUtils.wrapAvatarURL(path: self.detailImageURL))
        self.avatarImageView.kf.setImage(with: url)
        
        self.view.addSubview(avatarImageView)
        avatarImageView.snp.makeConstraints { make in
            make.size.equalTo(CGSizeMake(UIScreen.main.bounds.width, UIScreen.main.bounds.width))
            make.center.equalTo(self.view)
        }
    }
    
    @objc func rightItemPressed(){
        // 设置源为相机
        let alert = LGAlertView(title: nil, message: nil, style: .actionSheet, buttonTitles: ["拍照","从手机相册选择"], cancelButtonTitle: "取消", destructiveButtonTitle: nil, actionHandler: {alert,index, title in
            if index == 0 {
                self.takePhoto()
            } else if 1 == index {
                self.selectPhoto()
            }

        }, cancelHandler: { alertView in
            
        })
        alert.buttonsHeight = 40
        alert.cancelButtonOffsetY = 40
        alert.show()
        
    }
    
    override func updateColors() {
        view.setDynamicBackgroundColor()

    }
    
    func takePhoto(){
        let picker = UIImagePickerController()
        picker.sourceType = .camera
        picker.allowsEditing = true
        picker.delegate = self
        present(picker, animated: true)
    }
    
    func selectPhoto() {
        let picker = UIImagePickerController()
        picker.sourceType = .photoLibrary
        picker.allowsEditing = true
        picker.delegate = self
        present(picker, animated: true)
    }
    
}


extension MBDAvatarPickerViewController :UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true, completion: nil)
        guard let image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage else{
            return
        }
        self.avatarImageView.image = image
                
        let imageData = image.compressImage()
        
        self.startIndicatorAnimating()

        //先上传图片，再更新用户信息
        self.uploadPic(imageData: imageData) { error, picPath in
            //上传后判断结果
            if nil == error {
                //更新信息后判断结果
                self.updateUserInfo(picPath: picPath!) { er, result in
                    self.stopIndicatorAnimationg()

                    if nil == er {
                        self.view.makeToast("上传成功！")
                        
                        MBDAccountInfoModel.current()?.update(notify: true)
                    } else {
                        self.view.makeToast(er!.localizedDescription)
                    }
                    
                }
                
            } else {
                self.stopIndicatorAnimationg()
                self.view.makeToast(error?.localizedDescription)

            }
        }

    }
    
    func uploadPic(imageData : Data,completionHandler: @escaping (NSError?,String?) -> Void) {
        MBDHttpClient.shared.doUploadFileRequest("/oss/upload", data: imageData, fileName: "file").httpClientResponse { error, response in
            debugPrint(error ?? "")
            
            if nil == error {
                let rawDict = response?.rawDict
                let data : String = rawDict?["data"] as! String

                //返回值
                if data.isBlank {
                    completionHandler(error,nil)
                } else {
                    completionHandler(nil,data)
                }
                
            } else {
                //返回值
                completionHandler(error,nil)
            }
        }
    }
    
    func updateUserInfo(picPath : String,completionHandler: @escaping (NSError?, Bool?) -> Void){
        
        if let current = MBDAccountInfoModel.current() {
            var params : Dictionary<String, Any>
            params = ["userId":String(current.userId),"avatarUrl":String(picPath)]

            MBDHttpClient.shared.request("/user/update",method: .put,parameters: params,encoding: JSONEncoding.default).httpClientResponse { error, response in
                
                if nil != error {
                    completionHandler(error,false)
                } else {
                    completionHandler(nil,true)
                }
            }
        } else {
            let error : NSError = NSError(domain: "do not login", code: 10000)
            completionHandler(error,false)
        }
    }
    
}
